using System;
using System.IO;
using System.Runtime.Remoting;

namespace Be.Timvw.Framework.Remoting
{
    public static class RemotingHelper
    {
        static RemotingHelper()
        {
            string configurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

            if(File.Exists(configurationFile))
            {
                RemotingConfiguration.Configure(configurationFile, false);
            }
        }

        private static object GetService(string fullName)
        {
            WellKnownClientTypeEntry[] wellKnownClientTypeEntries = RemotingConfiguration.GetRegisteredWellKnownClientTypes();
            foreach(WellKnownClientTypeEntry welknownClientTypeEntry in wellKnownClientTypeEntries)
            {
                if(welknownClientTypeEntry.ObjectType.FullName == fullName)
                {
                    return Activator.GetObject(welknownClientTypeEntry.ObjectType, welknownClientTypeEntry.ObjectUrl);
                }
            }

            throw new ArgumentException(fullName + " is not a wellKnownClientType.");
        }

        public static T GetService<T>()
        {
            return (T) GetService(typeof(T).FullName);
        }
    }
}